"""
性能监控仪表板 - 实时展示系统性能指标
"""
import asyncio
import json
import time
from datetime import datetime, timedelta
from typing import Dict, Any, List, Optional
from collections import deque
from dataclasses import dataclass
import aiohttp
from aiohttp import web
import aiohttp_cors

from loguru import logger
from utils.constants import AgentType


@dataclass
class MetricPoint:
    """指标数据点"""
    timestamp: datetime
    value: float
    
    def to_dict(self) -> Dict[str, Any]:
        return {
            'timestamp': self.timestamp.isoformat(),
            'value': self.value
        }


class MetricsCollector:
    """指标收集器"""
    
    def __init__(self, max_points: int = 1000):
        self.max_points = max_points
        
        # 响应时间指标
        self.response_time_metrics: Dict[str, deque] = {
            'mean': deque(maxlen=max_points),
            'p90': deque(maxlen=max_points),
            'p95': deque(maxlen=max_points),
            'p99': deque(maxlen=max_points)
        }
        
        # 吞吐量指标
        self.throughput_metrics: Dict[str, deque] = {
            'requests_per_second': deque(maxlen=max_points),
            'requests_per_minute': deque(maxlen=max_points)
        }
        
        # 错误率指标
        self.error_rate_metrics: Dict[str, deque] = {
            'error_rate': deque(maxlen=max_points),
            'timeout_rate': deque(maxlen=max_points)
        }
        
        # 资源使用指标
        self.resource_metrics: Dict[str, deque] = {
            'cpu_usage': deque(maxlen=max_points),
            'memory_usage': deque(maxlen=max_points),
            'disk_io': deque(maxlen=max_points),
            'network_io': deque(maxlen=max_points)
        }
        
        # 智能体特定指标
        self.agent_metrics: Dict[str, Dict[str, deque]] = {}
        
        # 汇总统计
        self.summary_stats = {
            'total_requests': 0,
            'successful_requests': 0,
            'failed_requests': 0,
            'timeout_requests': 0,
            'start_time': datetime.utcnow()
        }
    
    def add_response_time_metrics(self, mean_rt: float, p90_rt: float, p95_rt: float, p99_rt: float):
        """添加响应时间指标"""
        now = datetime.utcnow()
        
        self.response_time_metrics['mean'].append(MetricPoint(now, mean_rt))
        self.response_time_metrics['p90'].append(MetricPoint(now, p90_rt))
        self.response_time_metrics['p95'].append(MetricPoint(now, p95_rt))
        self.response_time_metrics['p99'].append(MetricPoint(now, p99_rt))
    
    def add_throughput_metrics(self, rps: float, rpm: float):
        """添加吞吐量指标"""
        now = datetime.utcnow()
        
        self.throughput_metrics['requests_per_second'].append(MetricPoint(now, rps))
        self.throughput_metrics['requests_per_minute'].append(MetricPoint(now, rpm))
    
    def add_error_metrics(self, error_rate: float, timeout_rate: float):
        """添加错误率指标"""
        now = datetime.utcnow()
        
        self.error_rate_metrics['error_rate'].append(MetricPoint(now, error_rate))
        self.error_rate_metrics['timeout_rate'].append(MetricPoint(now, timeout_rate))
    
    def add_resource_metrics(self, cpu_usage: float, memory_usage: float, 
                           disk_io: float = 0, network_io: float = 0):
        """添加资源使用指标"""
        now = datetime.utcnow()
        
        self.resource_metrics['cpu_usage'].append(MetricPoint(now, cpu_usage))
        self.resource_metrics['memory_usage'].append(MetricPoint(now, memory_usage))
        self.resource_metrics['disk_io'].append(MetricPoint(now, disk_io))
        self.resource_metrics['network_io'].append(MetricPoint(now, network_io))
    
    def add_agent_metrics(self, agent_type: str, metrics: Dict[str, float]):
        """添加智能体特定指标"""
        now = datetime.utcnow()
        
        if agent_type not in self.agent_metrics:
            self.agent_metrics[agent_type] = {
                'task_count': deque(maxlen=self.max_points),
                'success_rate': deque(maxlen=self.max_points),
                'avg_response_time': deque(maxlen=self.max_points)
            }
        
        agent_data = self.agent_metrics[agent_type]
        agent_data['task_count'].append(MetricPoint(now, metrics.get('task_count', 0)))
        agent_data['success_rate'].append(MetricPoint(now, metrics.get('success_rate', 0)))
        agent_data['avg_response_time'].append(MetricPoint(now, metrics.get('avg_response_time', 0)))

    def push_metrics(self, metrics: Dict[str, Any]):
        """推送指标数据到收集器"""
        try:
            now = datetime.utcnow()
            
            # 处理响应时间指标
            if 'response_time' in metrics:
                rt = metrics['response_time']
                self.response_time_metrics['mean'].append(MetricPoint(now, rt))
                self.response_time_metrics['p90'].append(MetricPoint(now, rt * 0.9))
                self.response_time_metrics['p95'].append(MetricPoint(now, rt * 0.95))
                self.response_time_metrics['p99'].append(MetricPoint(now, rt * 0.99))
            
            # 处理吞吐量指标
            if 'throughput_rps' in metrics:
                self.throughput_metrics['requests_per_second'].append(MetricPoint(now, metrics['throughput_rps']))
            
            if 'throughput_rpm' in metrics:
                self.throughput_metrics['requests_per_minute'].append(MetricPoint(now, metrics['throughput_rpm']))
            
            # 处理错误率指标
            if 'error_rate' in metrics:
                self.error_rate_metrics['error_rate'].append(MetricPoint(now, metrics['error_rate']))
            
            if 'timeout_rate' in metrics:
                self.error_rate_metrics['timeout_rate'].append(MetricPoint(now, metrics['timeout_rate']))
            
            # 处理资源使用指标
            if 'cpu_usage' in metrics:
                self.resource_metrics['cpu_usage'].append(MetricPoint(now, metrics['cpu_usage']))
            
            if 'memory_usage' in metrics:
                self.resource_metrics['memory_usage'].append(MetricPoint(now, metrics['memory_usage']))
            
            if 'disk_io' in metrics:
                self.resource_metrics['disk_io'].append(MetricPoint(now, metrics['disk_io']))
            
            if 'network_io' in metrics:
                self.resource_metrics['network_io'].append(MetricPoint(now, metrics['network_io']))
                
        except Exception as e:
            print(f"推送指标失败: {e}")

    def update_summary_stats(self, total_requests: int, successful_requests: int, 
                           failed_requests: int, timeout_requests: int):
        """更新汇总统计"""
        self.summary_stats.update({
            'total_requests': total_requests,
            'successful_requests': successful_requests,
            'failed_requests': failed_requests,
            'timeout_requests': timeout_requests
        })
    
    def get_current_metrics(self) -> Dict[str, Any]:
        """获取当前指标"""
        return {
            'response_time': {
                'current_mean': self._get_latest_value(self.response_time_metrics['mean']),
                'current_p90': self._get_latest_value(self.response_time_metrics['p90']),
                'current_p95': self._get_latest_value(self.response_time_metrics['p95']),
                'current_p99': self._get_latest_value(self.response_time_metrics['p99'])
            },
            'throughput': {
                'current_rps': self._get_latest_value(self.throughput_metrics['requests_per_second']),
                'current_rpm': self._get_latest_value(self.throughput_metrics['requests_per_minute'])
            },
            'error_rate': {
                'current_error_rate': self._get_latest_value(self.error_rate_metrics['error_rate']),
                'current_timeout_rate': self._get_latest_value(self.error_rate_metrics['timeout_rate'])
            },
            'resource_usage': {
                'current_cpu': self._get_latest_value(self.resource_metrics['cpu_usage']),
                'current_memory': self._get_latest_value(self.resource_metrics['memory_usage'])
            },
            'summary': self.summary_stats
        }
    
    def get_historical_data(self, time_range: str = '1h') -> Dict[str, Any]:
        """获取历史数据"""
        return {
            'response_time': self._convert_to_dict(self.response_time_metrics),
            'throughput': self._convert_to_dict(self.throughput_metrics),
            'error_rate': self._convert_to_dict(self.error_rate_metrics),
            'resource_usage': self._convert_to_dict(self.resource_metrics),
            'agent_metrics': {
                agent_type: self._convert_to_dict(metrics)
                for agent_type, metrics in self.agent_metrics.items()
            }
        }
    
    def _get_latest_value(self, metric_queue: deque) -> Optional[float]:
        """获取最新值"""
        if not metric_queue:
            return None
        return metric_queue[-1].value
    
    def _convert_to_dict(self, metrics_dict: Dict[str, deque]) -> Dict[str, List[Dict[str, Any]]]:
        """转换为字典格式"""
        result = {}
        for key, queue in metrics_dict.items():
            result[key] = [point.to_dict() for point in queue]
        return result


class PerformanceDashboard:
    """性能监控仪表板"""
    
    def __init__(self, host: str = 'localhost', port: int = 8080):
        self.host = host
        self.port = port
        self.app = web.Application()
        self.collector = MetricsCollector()
        self.is_running = False
        
        # 设置CORS
        cors = aiohttp_cors.setup(self.app, defaults={
            "*": aiohttp_cors.ResourceOptions(
                allow_credentials=True,
                expose_headers="*",
                allow_headers="*",
                allow_methods="*"
            )
        })
        
        # 添加路由
        self._setup_routes(cors)
    
    def _setup_routes(self, cors):
        """设置路由"""
        # API路由
        api_routes = [
            web.get('/api/metrics/current', self.get_current_metrics),
            web.get('/api/metrics/historical', self.get_historical_metrics),
            web.get('/api/metrics/agents', self.get_agent_metrics),
            web.get('/api/metrics/summary', self.get_summary_metrics),
            web.post('/api/metrics/push', self.push_metrics),
        ]
        
        # 仪表板页面路由
        dashboard_routes = [
            web.get('/', self.dashboard_page),
            web.get('/dashboard', self.dashboard_page),
            web.get('/api/docs', self.api_docs),
        ]
        
        # 添加所有路由
        for route in api_routes + dashboard_routes:
            cors.add(self.app.router.add_route(route.method, route.path, route.handler))
    
    async def dashboard_page(self, request):
        """仪表板页面"""
        html_content = """
        <!DOCTYPE html>
        <html lang="zh-CN">
        <head>
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <title>MAESS 性能监控仪表板</title>
            <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
            <style>
                * {
                    margin: 0;
                    padding: 0;
                    box-sizing: border-box;
                }
                
                body {
                    font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
                    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
                    min-height: 100vh;
                    color: #333;
                }
                
                .container {
                    max-width: 1400px;
                    margin: 0 auto;
                    padding: 20px;
                }
                
                .header {
                    text-align: center;
                    color: white;
                    margin-bottom: 30px;
                }
                
                .header h1 {
                    font-size: 2.5em;
                    margin-bottom: 10px;
                    text-shadow: 2px 2px 4px rgba(0,0,0,0.3);
                }
                
                .header p {
                    font-size: 1.2em;
                    opacity: 0.9;
                }
                
                .metrics-grid {
                    display: grid;
                    grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
                    gap: 20px;
                    margin-bottom: 30px;
                }
                
                .metric-card {
                    background: white;
                    border-radius: 15px;
                    padding: 25px;
                    box-shadow: 0 10px 30px rgba(0,0,0,0.1);
                    transition: transform 0.3s ease, box-shadow 0.3s ease;
                    position: relative;
                    overflow: hidden;
                }
                
                .metric-card::before {
                    content: '';
                    position: absolute;
                    top: 0;
                    left: 0;
                    right: 0;
                    height: 4px;
                    background: linear-gradient(90deg, #007acc, #00d4ff);
                }
                
                .metric-card:hover {
                    transform: translateY(-5px);
                    box-shadow: 0 15px 40px rgba(0,0,0,0.15);
                }
                
                .metric-card h3 {
                    color: #007acc;
                    margin-bottom: 15px;
                    font-size: 1.3em;
                    font-weight: 600;
                }
                
                .metric-value {
                    font-size: 2.5em;
                    font-weight: bold;
                    color: #333;
                    margin-bottom: 5px;
                }
                
                .metric-unit {
                    color: #666;
                    font-size: 0.9em;
                    margin-bottom: 15px;
                }
                
                .metric-status {
                    padding: 5px 12px;
                    border-radius: 20px;
                    font-size: 0.85em;
                    font-weight: 600;
                    text-transform: uppercase;
                    letter-spacing: 0.5px;
                }
                
                .status-excellent {
                    background-color: #d4edda;
                    color: #155724;
                    border: 1px solid #c3e6cb;
                }
                
                .status-good {
                    background-color: #fff3cd;
                    color: #856404;
                    border: 1px solid #ffeaa7;
                }
                
                .status-warning {
                    background-color: #f8d7da;
                    color: #721c24;
                    border: 1px solid #f5c6cb;
                }
                
                .charts-container {
                    display: grid;
                    grid-template-columns: repeat(auto-fit, minmax(500px, 1fr));
                    gap: 30px;
                    margin-bottom: 30px;
                }
                
                .chart-card {
                    background: white;
                    border-radius: 15px;
                    padding: 25px;
                    box-shadow: 0 10px 30px rgba(0,0,0,0.1);
                }
                
                .chart-card h3 {
                    color: #007acc;
                    margin-bottom: 20px;
                    font-size: 1.4em;
                    font-weight: 600;
                }
                
                .chart-container {
                    position: relative;
                    height: 300px;
                }
                
                .status-bar {
                    background: white;
                    border-radius: 15px;
                    padding: 20px;
                    margin-bottom: 20px;
                    box-shadow: 0 5px 15px rgba(0,0,0,0.1);
                    display: flex;
                    justify-content: space-between;
                    align-items: center;
                    flex-wrap: wrap;
                }
                
                .status-item {
                    display: flex;
                    align-items: center;
                    margin: 5px 15px;
                }
                
                .status-indicator {
                    width: 12px;
                    height: 12px;
                    border-radius: 50%;
                    margin-right: 8px;
                }
                
                .status-online {
                    background-color: #28a745;
                    animation: pulse 2s infinite;
                }
                
                @keyframes pulse {
                    0% { opacity: 1; }
                    50% { opacity: 0.5; }
                    100% { opacity: 1; }
                }
                
                .refresh-info {
                    text-align: center;
                    color: white;
                    margin-top: 20px;
                    opacity: 0.8;
                }
                
                .loading {
                    display: inline-block;
                    width: 20px;
                    height: 20px;
                    border: 3px solid #f3f3f3;
                    border-top: 3px solid #007acc;
                    border-radius: 50%;
                    animation: spin 1s linear infinite;
                    margin-left: 10px;
                }
                
                @keyframes spin {
                    0% { transform: rotate(0deg); }
                    100% { transform: rotate(360deg); }
                }
                
                .error-message {
                    background-color: #f8d7da;
                    color: #721c24;
                    padding: 15px;
                    border-radius: 10px;
                    margin: 20px 0;
                    text-align: center;
                }
                
                @media (max-width: 768px) {
                    .metrics-grid {
                        grid-template-columns: 1fr;
                    }
                    
                    .charts-container {
                        grid-template-columns: 1fr;
                    }
                    
                    .header h1 {
                        font-size: 2em;
                    }
                }
            </style>
        </head>
        <body>
            <div class="container">
                <div class="header">
                    <h1>🚀 MAESS 性能监控仪表板</h1>
                    <p>实时智能体系统性能监控与分析</p>
                </div>
                
                <div class="status-bar">
                    <div class="status-item">
                        <div class="status-indicator status-online"></div>
                        <span>系统在线</span>
                    </div>
                    <div class="status-item">
                        <span id="current-time"></span>
                    </div>
                    <div class="status-item">
                        <span>数据更新中</span>
                        <div class="loading" id="loading-indicator"></div>
                    </div>
                </div>
                
                <div id="error-container"></div>
                
                <div class="metrics-grid" id="metrics-grid">
                    <!-- 动态生成的指标卡片 -->
                </div>
                
                <div class="charts-container">
                    <div class="chart-card">
                        <h3>📊 响应时间趋势</h3>
                        <div class="chart-container">
                            <canvas id="response-time-chart"></canvas>
                        </div>
                    </div>
                    
                    <div class="chart-card">
                        <h3>⚡ 吞吐量趋势</h3>
                        <div class="chart-container">
                            <canvas id="throughput-chart"></canvas>
                        </div>
                    </div>
                    
                    <div class="chart-card">
                        <h3>❌ 错误率趋势</h3>
                        <div class="chart-container">
                            <canvas id="error-rate-chart"></canvas>
                        </div>
                    </div>
                    
                    <div class="chart-card">
                        <h3>💻 资源使用趋势</h3>
                        <div class="chart-container">
                            <canvas id="resource-chart"></canvas>
                        </div>
                    </div>
                </div>
                
                <div class="refresh-info">
                    <p>数据每5秒自动刷新</p>
                </div>
            </div>
            
            <script>
                // 全局变量
                let charts = {};
                let updateInterval;
                
                // 初始化仪表板
                function initDashboard() {
                    initCharts();
                    updateMetrics();
                    startAutoUpdate();
                    updateCurrentTime();
                    setInterval(updateCurrentTime, 1000);
                }
                
                // 初始化图表
                function initCharts() {
                    const chartOptions = {
                        responsive: true,
                        maintainAspectRatio: false,
                        plugins: {
                            legend: {
                                position: 'top',
                            }
                        },
                        scales: {
                            x: {
                                type: 'time',
                                time: {
                                    displayFormats: {
                                        minute: 'HH:mm'
                                    }
                                }
                            },
                            y: {
                                beginAtZero: true
                            }
                        }
                    };
                    
                    // 响应时间图表
                    charts.responseTime = new Chart(document.getElementById('response-time-chart'), {
                        type: 'line',
                        data: {
                            datasets: [
                                {
                                    label: '平均响应时间 (ms)',
                                    data: [],
                                    borderColor: '#007acc',
                                    backgroundColor: 'rgba(0, 122, 204, 0.1)',
                                    tension: 0.4
                                },
                                {
                                    label: 'P99响应时间 (ms)',
                                    data: [],
                                    borderColor: '#e74c3c',
                                    backgroundColor: 'rgba(231, 76, 60, 0.1)',
                                    tension: 0.4
                                }
                            ]
                        },
                        options: chartOptions
                    });
                    
                    // 吞吐量图表
                    charts.throughput = new Chart(document.getElementById('throughput-chart'), {
                        type: 'line',
                        data: {
                            datasets: [
                                {
                                    label: '请求/秒',
                                    data: [],
                                    borderColor: '#2ecc71',
                                    backgroundColor: 'rgba(46, 204, 113, 0.1)',
                                    tension: 0.4
                                }
                            ]
                        },
                        options: chartOptions
                    });
                    
                    // 错误率图表
                    charts.errorRate = new Chart(document.getElementById('error-rate-chart'), {
                        type: 'line',
                        data: {
                            datasets: [
                                {
                                    label: '错误率 (%)',
                                    data: [],
                                    borderColor: '#e74c3c',
                                    backgroundColor: 'rgba(231, 76, 60, 0.1)',
                                    tension: 0.4
                                }
                            ]
                        },
                        options: chartOptions
                    });
                    
                    // 资源使用图表
                    charts.resource = new Chart(document.getElementById('resource-chart'), {
                        type: 'line',
                        data: {
                            datasets: [
                                {
                                    label: 'CPU使用率 (%)',
                                    data: [],
                                    borderColor: '#f39c12',
                                    backgroundColor: 'rgba(243, 156, 18, 0.1)',
                                    tension: 0.4
                                },
                                {
                                    label: '内存使用率 (%)',
                                    data: [],
                                    borderColor: '#9b59b6',
                                    backgroundColor: 'rgba(155, 89, 182, 0.1)',
                                    tension: 0.4
                                }
                            ]
                        },
                        options: chartOptions
                    });
                }
                
                // 更新指标
                async function updateMetrics() {
                    try {
                        const response = await fetch('/api/metrics/current');
                        const data = await response.json();
                        
                        updateMetricCards(data);
                        updateCharts(data);
                        
                        // 清除错误信息
                        document.getElementById('error-container').innerHTML = '';
                        
                    } catch (error) {
                        showError('获取指标数据失败: ' + error.message);
                    }
                }
                
                // 更新指标卡片
                function updateMetricCards(data) {
                    const metricsGrid = document.getElementById('metrics-grid');
                    
                    const metrics = [
                        {
                            title: '总请求数',
                            value: data.summary.total_requests.toLocaleString(),
                            unit: '个',
                            status: 'excellent'
                        },
                        {
                            title: '成功率',
                            value: ((data.summary.successful_requests / data.summary.total_requests) * 100).toFixed(1) + '%',
                            unit: '',
                            status: data.error_rate.current_error_rate < 1 ? 'excellent' : 'warning'
                        },
                        {
                            title: '平均响应时间',
                            value: data.response_time.current_mean ? data.response_time.current_mean.toFixed(0) : '0',
                            unit: 'ms',
                            status: data.response_time.current_mean < 200 ? 'excellent' : data.response_time.current_mean < 500 ? 'good' : 'warning'
                        },
                        {
                            title: 'P99响应时间',
                            value: data.response_time.current_p99 ? data.response_time.current_p99.toFixed(0) : '0',
                            unit: 'ms',
                            status: data.response_time.current_p99 < 500 ? 'excellent' : data.response_time.current_p99 < 1000 ? 'good' : 'warning'
                        },
                        {
                            title: '请求吞吐量',
                            value: data.throughput.current_rps ? data.throughput.current_rps.toFixed(1) : '0.0',
                            unit: 'req/s',
                            status: data.throughput.current_rps > 100 ? 'excellent' : data.throughput.current_rps > 50 ? 'good' : 'warning'
                        },
                        {
                            title: '错误率',
                            value: data.error_rate.current_error_rate ? data.error_rate.current_error_rate.toFixed(2) : '0.00',
                            unit: '%',
                            status: data.error_rate.current_error_rate < 1 ? 'excellent' : data.error_rate.current_error_rate < 5 ? 'good' : 'warning'
                        }
                    ];
                    
                    metricsGrid.innerHTML = metrics.map(metric => `
                        <div class="metric-card">
                            <h3>${metric.title}</h3>
                            <div class="metric-value">${metric.value}</div>
                            <div class="metric-unit">${metric.unit}</div>
                            <div class="metric-status status-${metric.status}">
                                ${metric.status === 'excellent' ? '优秀' : metric.status === 'good' ? '良好' : '需优化'}
                            </div>
                        </div>
                    `).join('');
                }
                
                // 更新图表
                function updateCharts(data) {
                    const now = new Date();
                    
                    // 更新响应时间图表
                    if (data.response_time.current_mean !== null) {
                        charts.responseTime.data.datasets[0].data.push({
                            x: now,
                            y: data.response_time.current_mean
                        });
                        
                        charts.responseTime.data.datasets[1].data.push({
                            x: now,
                            y: data.response_time.current_p99
                        });
                        
                        // 保持数据点数量
                        const maxPoints = 50;
                        if (charts.responseTime.data.datasets[0].data.length > maxPoints) {
                            charts.responseTime.data.datasets[0].data.shift();
                            charts.responseTime.data.datasets[1].data.shift();
                        }
                        
                        charts.responseTime.update('none');
                    }
                    
                    // 更新吞吐量图表
                    if (data.throughput.current_rps !== null) {
                        charts.throughput.data.datasets[0].data.push({
                            x: now,
                            y: data.throughput.current_rps
                        });
                        
                        if (charts.throughput.data.datasets[0].data.length > 50) {
                            charts.throughput.data.datasets[0].data.shift();
                        }
                        
                        charts.throughput.update('none');
                    }
                    
                    // 更新错误率图表
                    if (data.error_rate.current_error_rate !== null) {
                        charts.errorRate.data.datasets[0].data.push({
                            x: now,
                            y: data.error_rate.current_error_rate
                        });
                        
                        if (charts.errorRate.data.datasets[0].data.length > 50) {
                            charts.errorRate.data.datasets[0].data.shift();
                        }
                        
                        charts.errorRate.update('none');
                    }
                    
                    // 更新资源使用图表
                    if (data.resource_usage.current_cpu !== null) {
                        charts.resource.data.datasets[0].data.push({
                            x: now,
                            y: data.resource_usage.current_cpu
                        });
                        
                        if (charts.resource.data.datasets[0].data.length > 50) {
                            charts.resource.data.datasets[0].data.shift();
                        }
                        
                        charts.resource.update('none');
                    }
                }
                
                // 显示错误信息
                function showError(message) {
                    document.getElementById('error-container').innerHTML = `
                        <div class="error-message">
                            <strong>⚠️ 错误</strong><br>
                            ${message}
                        </div>
                    `;
                }
                
                // 更新当前时间
                function updateCurrentTime() {
                    const now = new Date();
                    document.getElementById('current-time').textContent = 
                        now.toLocaleString('zh-CN', {
                            year: 'numeric',
                            month: '2-digit',
                            day: '2-digit',
                            hour: '2-digit',
                            minute: '2-digit',
                            second: '2-digit'
                        });
                }
                
                // 开始自动更新
                function startAutoUpdate() {
                    updateInterval = setInterval(updateMetrics, 5000);
                }
                
                // 页面加载完成后初始化
                document.addEventListener('DOMContentLoaded', initDashboard);
            </script>
        </body>
        </html>
        """
        
        return web.Response(text=html_content, content_type='text/html')
    
    async def get_current_metrics(self, request):
        """获取当前指标"""
        try:
            current_metrics = self.collector.get_current_metrics()
            return web.json_response(current_metrics)
        except Exception as e:
            logger.error(f"获取当前指标失败: {str(e)}")
            return web.json_response({'error': str(e)}, status=500)
    
    async def get_historical_metrics(self, request):
        """获取历史指标"""
        try:
            time_range = request.query.get('range', '1h')
            historical_data = self.collector.get_historical_data(time_range)
            return web.json_response(historical_data)
        except Exception as e:
            logger.error(f"获取历史指标失败: {str(e)}")
            return web.json_response({'error': str(e)}, status=500)
    
    async def get_agent_metrics(self, request):
        """获取智能体指标"""
        try:
            agent_type = request.query.get('agent_type')
            agent_metrics = self.collector.agent_metrics
            
            if agent_type and agent_type in agent_metrics:
                return web.json_response({
                    agent_type: self.collector._convert_to_dict(agent_metrics[agent_type])
                })
            else:
                return web.json_response({
                    agent_type: self.collector._convert_to_dict(metrics)
                    for agent_type, metrics in agent_metrics.items()
                })
        except Exception as e:
            logger.error(f"获取智能体指标失败: {str(e)}")
            return web.json_response({'error': str(e)}, status=500)
    
    async def get_summary_metrics(self, request):
        """获取汇总指标"""
        try:
            summary = self.collector.summary_stats
            return web.json_response(summary)
        except Exception as e:
            logger.error(f"获取汇总指标失败: {str(e)}")
            return web.json_response({'error': str(e)}, status=500)
    
    async def push_metrics(self, request):
        """推送指标数据"""
        try:
            data = await request.json()
            
            # 处理响应时间指标
            if 'response_time' in data:
                rt_data = data['response_time']
                self.collector.add_response_time_metrics(
                    rt_data.get('mean', 0),
                    rt_data.get('p90', 0),
                    rt_data.get('p95', 0),
                    rt_data.get('p99', 0)
                )
            
            # 处理吞吐量指标
            if 'throughput' in data:
                tp_data = data['throughput']
                self.collector.add_throughput_metrics(
                    tp_data.get('rps', 0),
                    tp_data.get('rpm', 0)
                )
            
            # 处理错误率指标
            if 'error_rate' in data:
                er_data = data['error_rate']
                self.collector.add_error_metrics(
                    er_data.get('error_rate', 0),
                    er_data.get('timeout_rate', 0)
                )
            
            # 处理资源使用指标
            if 'resource_usage' in data:
                ru_data = data['resource_usage']
                self.collector.add_resource_metrics(
                    ru_data.get('cpu_usage', 0),
                    ru_data.get('memory_usage', 0),
                    ru_data.get('disk_io', 0),
                    ru_data.get('network_io', 0)
                )
            
            # 处理智能体指标
            if 'agent_metrics' in data:
                for agent_type, metrics in data['agent_metrics'].items():
                    self.collector.add_agent_metrics(agent_type, metrics)
            
            # 更新汇总统计
            if 'summary' in data:
                summary = data['summary']
                self.collector.update_summary_stats(
                    summary.get('total_requests', 0),
                    summary.get('successful_requests', 0),
                    summary.get('failed_requests', 0),
                    summary.get('timeout_requests', 0)
                )
            
            return web.json_response({'status': 'success'})
            
        except Exception as e:
            logger.error(f"推送指标失败: {str(e)}")
            return web.json_response({'error': str(e)}, status=500)
    
    async def api_docs(self, request):
        """API文档页面"""
        docs_html = """
        <!DOCTYPE html>
        <html lang="zh-CN">
        <head>
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <title>MAESS 性能监控 API 文档</title>
            <style>
                body {
                    font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
                    line-height: 1.6;
                    margin: 0;
                    padding: 20px;
                    background-color: #f5f5f5;
                }
                .container {
                    max-width: 1200px;
                    margin: 0 auto;
                    background: white;
                    padding: 30px;
                    border-radius: 10px;
                    box-shadow: 0 0 20px rgba(0,0,0,0.1);
                }
                .endpoint {
                    background-color: #f8f9fa;
                    border-left: 4px solid #007acc;
                    padding: 20px;
                    margin: 20px 0;
                    border-radius: 5px;
                }
                .method {
                    background-color: #28a745;
                    color: white;
                    padding: 3px 8px;
                    border-radius: 3px;
                    font-weight: bold;
                    font-size: 0.9em;
                }
                .method.get { background-color: #007bff; }
                .method.post { background-color: #28a745; }
                code {
                    background-color: #e9ecef;
                    padding: 2px 6px;
                    border-radius: 3px;
                    font-family: 'Courier New', monospace;
                }
                pre {
                    background-color: #f8f9fa;
                    padding: 15px;
                    border-radius: 5px;
                    overflow-x: auto;
                    border: 1px solid #e9ecef;
                }
            </style>
        </head>
        <body>
            <div class="container">
                <h1>📊 MAESS 性能监控 API 文档</h1>
                <p>本API提供MAESS智能体系统的实时性能监控数据。</p>
                
                <div class="endpoint">
                    <h3><span class="method get">GET</span> /api/metrics/current</h3>
                    <p>获取当前性能指标</p>
                    <h4>响应示例:</h4>
                    <pre><code>{
    "response_time": {
        "current_mean": 150.5,
        "current_p90": 250.3,
        "current_p95": 320.1,
        "current_p99": 450.8
    },
    "throughput": {
        "current_rps": 125.3,
        "current_rpm": 7518.0
    },
    "error_rate": {
        "current_error_rate": 0.5,
        "current_timeout_rate": 0.1
    },
    "resource_usage": {
        "current_cpu": 45.2,
        "current_memory": 62.8
    },
    "summary": {
        "total_requests": 12543,
        "successful_requests": 12480,
        "failed_requests": 63,
        "timeout_requests": 12
    }
}</code></pre>
                </div>
                
                <div class="endpoint">
                    <h3><span class="method get">GET</span> /api/metrics/historical?range=1h</h3>
                    <p>获取历史性能指标</p>
                    <p>参数: <code>range</code> - 时间范围 (1h, 6h, 24h, 7d)</p>
                </div>
                
                <div class="endpoint">
                    <h3><span class="method get">GET</span> /api/metrics/agents?agent_type=text_qa</h3>
                    <p>获取智能体特定指标</p>
                    <p>参数: <code>agent_type</code> - 智能体类型 (可选)</p>
                </div>
                
                <div class="endpoint">
                    <h3><span class="method get">GET</span> /api/metrics/summary</h3>
                    <p>获取系统汇总统计</p>
                </div>
                
                <div class="endpoint">
                    <h3><span class="method post">POST</span> /api/metrics/push</h3>
                    <p>推送性能指标数据</p>
                    <h4>请求体示例:</h4>
                    <pre><code>{
    "response_time": {
        "mean": 150.5,
        "p90": 250.3,
        "p95": 320.1,
        "p99": 450.8
    },
    "throughput": {
        "rps": 125.3,
        "rpm": 7518.0
    },
    "error_rate": {
        "error_rate": 0.5,
        "timeout_rate": 0.1
    },
    "resource_usage": {
        "cpu_usage": 45.2,
        "memory_usage": 62.8
    },
    "summary": {
        "total_requests": 12543,
        "successful_requests": 12480,
        "failed_requests": 63,
        "timeout_requests": 12
    }
}</code></pre>
                </div>
                
                <p><a href="/">← 返回仪表板</a></p>
            </div>
        </body>
        </html>
        """
        
        return web.Response(text=docs_html, content_type='text/html')
    
    async def start(self):
        """启动仪表板"""
        if self.is_running:
            logger.warning("性能监控仪表板已在运行")
            return
        
        try:
            runner = web.AppRunner(self.app)
            await runner.setup()
            
            site = web.TCPSite(runner, self.host, self.port)
            await site.start()
            
            self.is_running = True
            logger.info(f"性能监控仪表板已启动: http://{self.host}:{self.port}")
            logger.info(f"API文档: http://{self.host}:{self.port}/api/docs")
            
        except Exception as e:
            logger.error(f"启动性能监控仪表板失败: {str(e)}")
            raise
    
    async def stop(self):
        """停止仪表板"""
        if not self.is_running:
            return
        
        try:
            await self.app.cleanup()
            self.is_running = False
            logger.info("性能监控仪表板已停止")
            
        except Exception as e:
            logger.error(f"停止性能监控仪表板失败: {str(e)}")


# 使用示例
async def run_performance_dashboard():
    """运行性能监控仪表板"""
    
    dashboard = PerformanceDashboard(host='localhost', port=8080)
    
    try:
        await dashboard.start()
        
        # 保持运行
        while True:
            await asyncio.sleep(1)
            
    except KeyboardInterrupt:
        logger.info("收到停止信号，正在关闭仪表板...")
        await dashboard.stop()
    
    except Exception as e:
        logger.error(f"仪表板运行出错: {str(e)}")
        await dashboard.stop()


if __name__ == "__main__":
    print("性能监控仪表板已加载")
    print("使用 run_performance_dashboard() 函数启动仪表板")
    print("或使用 PerformanceDashboard 类自定义配置")